<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * update project title
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Gospecies\Controller;

use Zend\View\Model\JsonModel;
use Gospecies\Controller\AbstractIdentityJsonController;


class AjaxUpdateProjectJsonController extends AbstractIdentityJsonController
{

    public function indexAction()
    {
        // get logged user
        $this->user = $this->get_identity();

        try {
              $error  = array();
              $params = array();

              $params = array('id_project' => $this->request->getPost()->id_project,
                              'data'       => array('title'       => $this->request->getPost()->project_name,
                                                    'id_modifier' => $this->user->id_user));

              if (empty($params['id_project']) || ($params['id_project'] === null)) {
                  $error[] = 'id_project name isnt defined or empty';
              }

              // check permission if id_group is "contributor" or above.
              // users of those groups can only update own projects
              //
              if ((isset($this->user->id_group) && ((int)$this->user->id_status == 200))) {
                  if ((int)$this->user->id_group >= 300) {

                      $ProjectGet = $this->CoreModel('ProjectGet');

                      $params2  = array('id_project' => $params['id_project']);

                      $result  = $ProjectGet->run( $params2 );

                      if (isset($result['id_owner'])) {
                          if ($this->user->id_user !== $result['id_owner']) {
                              return new JsonModel(array('error' => 'permission denied'));
                          }
                      } else {
                          return new JsonModel(array('error' => 'id_project dosent exists: ' . $params['id_project']));
                      }
                  }
              } else {
                  return new JsonModel(array('error' => 'permission denied'));
              }

              if (empty($params['data']['title']) || ($params['data']['title'] === null)) {
                  $error[] = 'Project name isnt defined or empty';
              }

              $ProjectUpdate = $this->CoreModel('ProjectUpdate');

              $ProjectUpdate->run( $params );

              return new JsonModel(array('updateProject' => 'ok'));

        } catch (\Exception $e) {

            $this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->__toString();

            return new JsonModel(array('error' => $this->default_error));

        }
    }
}
